<!--
  SOP通知记录管理页面
  @description 通知记录的列表页面，包含搜索、表格、分页、重试等功能
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
      class="-mb-15px"
    >
      <el-form-item :label="t('sop.notify.appId')" prop="appId">
        <el-select
          v-model="queryParams.appId"
          :placeholder="t('sop.common.pleaseSelect') + t('sop.notify.appId')"
          clearable
          style="width: 200px"
          filterable
          remote
          :remote-method="searchApps"
          :loading="appLoading"
        >
          <el-option
            v-for="app in appOptions"
            :key="app.id"
            :label="`${app.appName}(${app.appId})`"
            :value="app.appId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('sop.notify.merchantNo')" prop="merchantNo">
        <el-input
          v-model="queryParams.merchantNo"
          :placeholder="t('sop.common.pleaseInput') + t('sop.notify.merchantNo')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('sop.notify.notifyType')" prop="notifyType">
        <el-select
          v-model="queryParams.notifyType"
          :placeholder="t('sop.common.pleaseSelect') + t('sop.notify.notifyType')"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="(label, value) in notifyTypeOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('sop.notify.notifyStatus')" prop="notifyStatus">
        <el-select
          v-model="queryParams.notifyStatus"
          :placeholder="t('sop.common.pleaseSelect') + t('sop.notify.notifyStatus')"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="(label, value) in notifyStatusOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('sop.notify.createTime')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="datetimerange"
          :start-placeholder="t('sop.common.startTime')"
          :end-placeholder="t('sop.common.endTime')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('sop.common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('sop.common.reset') }}
        </el-button>
        <el-button
          type="success"
          v-hasPermi="['sop:notify:retry']"
          @click="handleBatchRetry"
          :disabled="!multipleSelection.length"
        >
          <Icon icon="ep:refresh-right" class="mr-5px" />
          {{ t('sop.notify.batchRetry') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        :label="t('sop.notify.id')"
        align="center"
        prop="id"
        width="80"
      />
      <el-table-column
        :label="t('sop.notify.appId')"
        align="center"
        prop="appId"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column
        :label="t('sop.notify.merchantNo')"
        align="center"
        prop="merchantNo"
        width="120"
      />
      <el-table-column
        :label="t('sop.notify.notifyType')"
        align="center"
        prop="notifyType"
        width="120"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SOP_NOTIFY_TYPE" :value="scope.row.notifyType" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('sop.notify.notifyUrl')"
        align="center"
        prop="notifyUrl"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        :label="t('sop.notify.notifyStatus')"
        align="center"
        prop="notifyStatus"
        width="120"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SOP_NOTIFY_STATUS" :value="scope.row.notifyStatus" />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('sop.notify.retryCount')"
        align="center"
        prop="retryCount"
        width="100"
      >
        <template #default="scope">
          <el-tag :type="scope.row.retryCount > 3 ? 'danger' : 'info'">
            {{ scope.row.retryCount }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('sop.notify.createTime')"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column
        :label="t('sop.notify.lastNotifyTime')"
        align="center"
        prop="lastNotifyTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column :label="t('sop.common.action')" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
            v-hasPermi="['sop:notify:query']"
          >
            {{ t('sop.common.detail') }}
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleRetry(scope.row)"
            v-hasPermi="['sop:notify:retry']"
            :disabled="scope.row.notifyStatus === 1"
          >
            {{ t('sop.notify.retry') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 通知详情对话框 -->
  <NotifyDetail ref="detailRef" />
</template>

<script setup lang="ts" name="SopNotify">
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import * as NotifyApi from '@/api/sop/notify'
import * as AppApi from '@/api/sop/app'
import NotifyDetail from './NotifyDetail.vue'
import { NotifyVO } from '@/api/sop/types'

/** 通知记录管理 */
defineOptions({ name: 'SopNotify' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref<NotifyVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  appId: undefined,
  merchantNo: undefined,
  notifyType: undefined,
  notifyStatus: undefined,
  createTime: undefined
})
const queryFormRef = ref() // 搜索的表单
const multipleSelection = ref<NotifyVO[]>([]) // 多选

// 应用选项
const appOptions = ref<any[]>([])
const appLoading = ref(false)

// 通知类型选项
const notifyTypeOptions = reactive({
  1: t('sop.notify.paymentNotify'),
  2: t('sop.notify.refundNotify'),
  3: t('sop.notify.settleNotify')
})

// 通知状态选项
const notifyStatusOptions = reactive({
  0: t('sop.notify.pending'),
  1: t('sop.notify.success'),
  2: t('sop.notify.failed')
})

// 详情组件引用
const detailRef = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await NotifyApi.getNotifyPageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: NotifyVO[]) => {
  multipleSelection.value = selection
}

/** 搜索应用 */
const searchApps = async (query: string) => {
  if (query) {
    appLoading.value = true
    try {
      const data = await AppApi.getAppListApi({ appName: query })
      appOptions.value = data
    } finally {
      appLoading.value = false
    }
  } else {
    appOptions.value = []
  }
}

/** 打开详情 */
const openDetail = (row: NotifyVO) => {
  detailRef.value.open(row)
}

/** 重试通知 */
const handleRetry = async (row: NotifyVO) => {
  try {
    await message.confirm(t('sop.notify.retryConfirm'))
    await NotifyApi.retryNotifyApi(row.id!)
    message.success(t('sop.notify.retrySuccess'))
    await getList()
  } catch {}
}

/** 批量重试 */
const handleBatchRetry = async () => {
  try {
    await message.confirm(t('sop.notify.batchRetryConfirm'))
    const ids = multipleSelection.value.map(item => item.id!)
    await NotifyApi.batchRetryNotifyApi(ids)
    message.success(t('sop.notify.batchRetrySuccess'))
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
